package com.service.impl;

import com.dto.UnloadGoodsDTO;
import com.entity.*;
import com.exception.RawsLackException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mapper.GoodsEntityMapper;
import com.mapper.ProducedMapper;
import com.mapper.UnloadGoodsMapper;
import com.service.OutGoodsService;
import com.service.ProducedService;
import com.service.UnloadGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Date;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class ProducedServiceImpl implements ProducedService {
    @Autowired
    ProducedMapper producedMapper;
    @Autowired
    UnloadGoodsMapper unloadGoodsMapper;
    @Autowired
    UnloadGoodsService unloadGoodsService;
    @Autowired
    GoodsEntityMapper goodsEntityMapper;
    @Autowired
    OutGoodsService outGoodsService;
    //  查询所有的生产单
    @Override
    public PageBean<ProductionOrder> findAll(int pageIndex, int pageSize, ProductionOrder productionOrder) {
        PageHelper.startPage(pageIndex,pageSize);

        List<ProductionOrder> productionOrders = producedMapper.findAll(productionOrder);
        PageInfo<ProductionOrder> pageInfo = new PageInfo<>(productionOrders);
        PageBean<ProductionOrder> pageBean = new PageBean<>();
        pageBean.setPageIndex(pageIndex);
        pageBean.setPageSize(pageSize);
        pageBean.setTotalPage(pageInfo.getPages());
        pageBean.setTotalRecord((int) pageInfo.getTotal());
        pageBean.setBeanList(pageInfo.getList());
        return pageBean;
    }
    //  查询所有生产部门
    @Override
    public List<Department> findAllDept() {
        Set<Department> departments = new HashSet<>(producedMapper.findAllDept());
        return new ArrayList<>(departments);
    }
    //  创建生产单
    @Override
    public void add(ProductionOrder productionOrder) {
        int i = 00000;
        //  获取所有生产订单
        List<ProductionOrder> productionOrders = producedMapper.findAll2();
        if (productionOrders.size()!=0){
            //  获取最后的生产单
            ProductionOrder nproductionOrder= productionOrders.get(productionOrders.size()-1);
            //  获取最后一个生产单的单号
            String number = nproductionOrder.getPoid();
            //  分割出里面的数字
            String[] strings = number.split("-");
            i = Integer.valueOf(strings[1])+1;
        }else {
            i++;
        }
        //  生成新的生产单号
        productionOrder.setPoid("yj"+"-"+i);
        productionOrder.setPstate("待生产");
        productionOrder.setYield(productionOrder.getPnum()+productionOrder.getPunit());
        producedMapper.add(productionOrder);

    }
    //  修改生产单
    @Override
    public void modify(ProductionOrder productionOrder) {
        productionOrder.setYield(productionOrder.getPnum()+productionOrder.getPunit());
        producedMapper.modify(productionOrder);
    }
    //  删除生产单
    @Override
    public void delete(ProductionOrder productionOrder) {
        producedMapper.delete(productionOrder);
    }
    //  批量删除生产单
    @Override
    public void deleteBatch(int[] ids) {
        producedMapper.deleteBatch(ids);
    }



    //  查询所有的生产领料
    @Override
    public PageBean<ProductionReceive> findAllReceive(int pageIndex, int pageSize, ProductionReceive productionReceive) {
        PageHelper.startPage(pageIndex,pageSize);

        List<ProductionReceive> productionReceives = producedMapper.findAllReceive(productionReceive);
        PageInfo<ProductionReceive> pageInfo = new PageInfo<>(productionReceives);
        PageBean<ProductionReceive> pageBean = new PageBean<>();
        pageBean.setPageIndex(pageIndex);
        pageBean.setPageSize(pageSize);
        pageBean.setTotalPage(pageInfo.getPages());
        pageBean.setTotalRecord((int) pageInfo.getTotal());
        pageBean.setBeanList(pageInfo.getList());
        return pageBean;
    }
    //  添加生产领料
    @Override
    public void addReceive(ProductionReceive productionReceive) {
        int i = 0;
        //  获取所有生产领料
        List<ProductionReceive> productionReceives = producedMapper.findAllReceive2();
        if (productionReceives.size()!=0){
            //  获取最后的生产单
            ProductionReceive receive = productionReceives.get(productionReceives.size() - 1);
            //  获取最后一个生产单的单号
            String number = receive.getPmid();
            //  分割出里面的数字
            String[] strings = number.split("-");
            i = Integer.valueOf(strings[1])+1;
        }else {
            i++;
        }
        //  生成新的生产单号
        productionReceive.setPmid("LL"+"-00"+i);
        productionReceive.setMstate("未领取");
        productionReceive.setAstate("待审批");
        productionReceive.setMyield(productionReceive.getMnum()+productionReceive.getMunit());
        producedMapper.addReceive(productionReceive);
    }
    //  修改生产领料
    @Override
    public void modifyReceive(ProductionReceive productionReceive) {
        //  获取商品唯一标识
        GoodsEntity goodsEntity = new GoodsEntity();
        goodsEntity.setGname(productionReceive.getMname());
        int num = Integer.parseInt(productionReceive.getMnum());
        //  获取商品的单位
        if(productionReceive.getMunit().equals("吨")){
            num = num*1000;
        }
        OutGoods outGoods = new OutGoods(null,productionReceive.getMname(),num,null,goodsEntityMapper.selectAll(goodsEntity).get(0).getGoodsUniqueNo(),null,null,null);
        System.out.println(outGoods+"出库");
        //  从仓库出库
        outGoodsService.outGoods(outGoods);
        //  获取新添加的原料
        ProductionStore addStore = new ProductionStore(productionReceive.getMname(), productionReceive.getMnum(),
                productionReceive.getMunit(), null,"原料",null,null,null);

        //  查询原本有多少原料
        ProductionStore originstore = producedMapper.findProducedStoreBySname(addStore);

        String newsnum = "";
        if (addStore.getSunit().equals("吨")){
            //  获取增加后的数量
            newsnum = String.valueOf(Double.valueOf(originstore.getSnum())+Double.valueOf(addStore.getSnum()));
        } else if (addStore.getSunit().equals("千克")) {
            //  获取增加后的数量
            newsnum = String.valueOf(Double.valueOf(originstore.getSnum())+(Double.valueOf(addStore.getSnum())/1000));
        }
        //  修改库存
        addStore.setSyield(newsnum+"吨");
        addStore.setSunit("吨");
        addStore.setSnum(newsnum);
        productionReceive.setAstate("已通过");
        producedMapper.modifyProducedStore(addStore);
        //  修改生成领料单
        productionReceive.setMyield(productionReceive.getMnum()+productionReceive.getMunit());
        producedMapper.modifyReceive(productionReceive);
    }
    //  删除生产领料
    @Override
    public void deleteM(ProductionReceive productionReceive) {
        producedMapper.deleteM(productionReceive);
    }
    //  批量删除生产领料
    @Override
    public void deleteBatchM(int[] ids) {
        producedMapper.deleteBatchM(ids);
    }


    //  查询全部生产状况
    @Override
    public PageBean<ProductionProduced> findAllProduced(int pageIndex, int pageSize,ProductionProduced productionProduced) {
        PageHelper.startPage(pageIndex,pageSize);

        List<ProductionProduced> productionProduceds = producedMapper.findAllProduced(productionProduced);
        PageInfo<ProductionProduced> pageInfo = new PageInfo<>(productionProduceds);
        PageBean<ProductionProduced> pageBean = new PageBean<>();
        pageBean.setPageIndex(pageIndex);
        pageBean.setPageSize(pageSize);
        pageBean.setTotalPage(pageInfo.getPages());
        pageBean.setTotalRecord((int) pageInfo.getTotal());
        pageBean.setBeanList(pageInfo.getList());
        return pageBean;
    }

    //  查询全部产品
    @Override
    public List<ProductionGoods> findAllGoods() {
        return producedMapper.findAllGoods();
    }
    //  查询全部原料
    @Override
    public List<ProductionRaws> findAllRaws() {
        return producedMapper.findAllRaws();
    }
    //  根据id查询生产单
    public ProductionOrder findOrderById(int id) {
        return producedMapper.findOrder(id);
    }
    //  根据生产单原料及产品
    public Map<String, List<String>> findGoodsRawsByOrder(int id){
        //  获取生产单
        ProductionOrder order = producedMapper.findOrder(id);
        //  获取产品名
        String pname = order.getPname();
        String punit = order.getPunit();
        String pnum = order.getPnum();
        //  获取预计产量
        double num = Double.valueOf(pnum);
        //  获取适合生产的员工
        List<ProductionEmployee> employees = producedMapper.findEmployeesByDept(order);
        String ename = "";
        for (ProductionEmployee e:employees) {
            ename+= e.getEname()+"、";
        }
        String employee = ename.substring(0,ename.length()-1);

        //  获取原料
        Map<String, List<String>> rawsMap = new HashMap<>();
        //  2甲酸 + 3硼酸酐 = 1无水甲酸
        rawsMap.put("无水甲酸", List.of(employee,pnum+punit,"甲酸："+num*2+punit,"硼酸酐："+num*3+punit));
        //  3硫酸氢钠 + 2丙酮 + 1氰化钾 = 1丙酮氰醇
        rawsMap.put("丙酮氰醇", List.of(employee,pnum+punit,"硫酸氢钠："+num*3+punit,"丙酮："+num*2+punit,"氰化钾："+num+punit));
        //  2乙酰氯 + 1氰化铜 + 3乙腈 + 1乙醚= 1乙酰腈
        rawsMap.put("乙酰腈", List.of(employee,pnum+punit,"乙酰氯："+num*2+punit, "氰化铜："+num+punit,"乙腈："+num*3+punit,"乙醚："+num+punit));
        //  3三甲基氯硅烷 + 4烯丙基溴化镁 + 2乙醚 + 3格化试剂 = 1烯丙基三甲硅烷
        rawsMap.put("烯丙基三甲硅烷", List.of(employee,pnum+punit,"三甲基氯硅烷："+num*3+punit,"烯丙基溴化镁："+num*4+punit,"乙醚："+num*2+punit,"格化试剂："+num*3+punit));

        Map<String, List<String>> newMap = new HashMap<>();
        for (String key : rawsMap.keySet()) {
            if (key.equals(pname)){
                newMap.put(key, rawsMap.get(key));
            }
        }
        return newMap;
    }
    //  不同产品使用不同原料
    @Override
    public List<String> findRawsByGoods(int id) {
        Map<Integer, List<String>> rawsMap = new HashMap<>();
        rawsMap.put(1, List.of("甲酸", "硼酸酐"));
        rawsMap.put(2, List.of("硫酸氢钠", "丙酮","氰化钾"));
        rawsMap.put(3, List.of("乙酰氯", "氰化铜","乙腈","乙醚"));
        rawsMap.put(4, List.of("三甲基氯硅烷", "烯丙基溴化镁","乙醚","格化试剂"));

        List<String> raws = new ArrayList<>();
        if (rawsMap.containsKey(id)) {
            raws.addAll(rawsMap.get(id));
        }
        return raws;
    }
    //  获取所有未生产单
    @Override
    public List<ProductionOrder> findAllPoids() {
        return producedMapper.findAllPoids();
    }
    //  获取全部生产员工
    @Override
    public List<ProductionEmployee> findAllEmployees() {
        return producedMapper.findAllEmployees();
    }
    //  根据名字查询员工id
    @Override
    public List<ProductionEmployee> findEmployeeByName(String name) {
        return producedMapper.findEmployeeByName(name);
    }

    //  开始生产
    @Override
    public void addProduced(ProductionProduced productionProduced) {
        producedMapper.addProduced(productionProduced);
    }
    @Override
    public void modifyPstate(ProductionProduced productionProduced) {
        productionProduced.getOrder().setPstate("生产中");
        producedMapper.modifyPstate(productionProduced.getOrder());
    }
    //  删除生产情况
    @Override
    public void deleteProduced(ProductionProduced productionProduced) {
        producedMapper.deleteProduced(productionProduced);
    }
    //  批量删除生产情况
    @Override
    public void deleteBatchProduced(int[] ids) {
        producedMapper.deleteBatchProduced(ids);
    }

    //  通过id获取生产情况
    @Override
    public List<ProductionProduced> findProducedById(int id) {
        ProductionProduced productionProduced = new ProductionProduced();
        productionProduced.setId(id);
        return producedMapper.findAllProduced(productionProduced);
    }
    //  修改生产状态
    @Override
    public void modifyProduced(ProductionProduced productionProduced) {
        producedMapper.modifyProduced(productionProduced);
        producedMapper.modifyPstate(productionProduced.getOrder());
    }
    //  结束生产
    @Override
    public void overProduced(ProductionProduced productionProduced) {
        String rate="";
        String efficiency="";
        if (productionProduced.getOrder().getPunit().equals(productionProduced.getOrder().getPrunit())) {
            //  获取实际产量
            Double prnum = Double.valueOf(productionProduced.getOrder().getPrnum());
            //  获取计划产量
            Double pnum = Double.valueOf(productionProduced.getOrder().getPnum());
            //  计算完工率
            rate = String.valueOf(BigDecimal.valueOf((prnum / pnum * 100)).setScale(2, RoundingMode.HALF_UP)) + "%";
        }else if (productionProduced.getOrder().getPunit().equals("千克")){
            //  获取实际产量
            Double prnum = Double.valueOf(productionProduced.getOrder().getPrnum())*1000;
            //  获取计划产量
            Double pnum = Double.valueOf(productionProduced.getOrder().getPnum());
            //  计算完工率
            rate = String.valueOf(BigDecimal.valueOf((prnum / pnum * 100)).setScale(2, RoundingMode.HALF_UP)) + "%";
        }else {
            //  获取实际产量
            Double prnum = Double.valueOf(productionProduced.getOrder().getPrnum());
            //  获取计划产量
            Double pnum = Double.valueOf(productionProduced.getOrder().getPnum())*1000;
            //  计算完工率
            rate = String.valueOf(BigDecimal.valueOf((prnum / pnum * 100)).setScale(2, RoundingMode.HALF_UP)) + "%";
        }

        //  获取实际生产天数
        Date stime = productionProduced.getStime();
        Date ertime = productionProduced.getOrder().getErtime();
        // 计算 milliseconds 差
        long diffInMillies = ertime.getTime() - stime.getTime();
        // 转换为天数
        int days = (int) TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS)+1;
        String day = String.valueOf(days)+"天";

        //  获取生产效率
        if (productionProduced.getOrder().getPrunit().equals("千克")){
            //  获取实际产量
            Double prnum = Double.valueOf(productionProduced.getOrder().getPrnum());
            efficiency=String.valueOf(BigDecimal.valueOf(prnum / days).setScale(2, RoundingMode.HALF_UP))+"千克/天";
        }else {
            //  获取实际产量
            Double prnum = Double.valueOf(productionProduced.getOrder().getPrnum())*1000;
            efficiency=String.valueOf(BigDecimal.valueOf(prnum / days).setScale(2, RoundingMode.HALF_UP))+"千克/天";
        }
        //  获取预计产量
        String yield = productionProduced.getOrder().getPnum()+productionProduced.getOrder().getPunit();
        //  获取实际产量
        String ryield = productionProduced.getOrder().getPrnum()+productionProduced.getOrder().getPrunit();
        //  将完工率\生产天数、生产效率存储
        productionProduced.getOrder().setRate(rate);
        productionProduced.getOrder().setDays(day);
        productionProduced.getOrder().setEfficiency(efficiency);
        productionProduced.getOrder().setYield(yield);
        productionProduced.getOrder().setRyield(ryield);
        producedMapper.overProduced(productionProduced);
    }
    //  获取所有完成生产的情况
    @Override
    public PageBean<ProductionProduced> findAllProducedOver(int pageIndex, int pageSize,ProductionProduced productionProduced) {
        PageHelper.startPage(pageIndex,pageSize);
        List<ProductionProduced> productionProduceds = producedMapper.findAllProducedOver(productionProduced);

        PageInfo<ProductionProduced> pageInfo = new PageInfo<>(productionProduceds);
        PageBean<ProductionProduced> pageBean = new PageBean<>();
        pageBean.setPageIndex(pageIndex);
        pageBean.setPageSize(pageSize);
        pageBean.setTotalPage(pageInfo.getPages());
        pageBean.setTotalRecord((int) pageInfo.getTotal());
        pageBean.setBeanList(pageInfo.getList());
        return pageBean;
    }
    //  获取所有仓储情况
    @Override
    public List<ProductionStore> findAllProducedStore() {
        List<ProductionStore> producedStore = producedMapper.findAllProducedStore();
        for (ProductionStore s:producedStore) {
            if (Double.valueOf(s.getSnum())<100){
                s.setPressure("库存正常");
            }else {
                s.setPressure("需要入库");
            }
        }
        return producedStore;
    }
    //  修改仓储情况
    @Override
    public void modifyStore(ProductionStore productionStore) {
        //  查询原本有多少原料
        ProductionStore originstore = producedMapper.findProducedStoreBySname(productionStore);

        String newsnum = "";
        if (originstore.getSunit().equals(productionStore.getSunit())){
            if (productionStore.getStype().equals("原料")) {
                //  获取增加后的数量
                newsnum = String.valueOf(Double.valueOf(originstore.getSnum()) - Double.valueOf(productionStore.getSnum()));
                if (Double.valueOf(originstore.getSnum()) - Double.valueOf(productionStore.getSnum()) <0){
                    throw new RawsLackException("原料不足");
                }
            }else {
                //  获取增加后的数量
                newsnum = String.valueOf(Double.valueOf(originstore.getSnum()) + Double.valueOf(productionStore.getSnum()));
            }
        } else if (productionStore.getSunit().equals("千克")) {
            if (productionStore.getStype().equals("原料")) {
                //  获取增加后的数量
                newsnum = String.valueOf(Double.valueOf(originstore.getSnum()) - (Double.valueOf(productionStore.getSnum()) / 1000));
                if (Double.valueOf(originstore.getSnum()) - (Double.valueOf(productionStore.getSnum()) / 1000) <0){
                    throw new RawsLackException("原料不足");
                }
                System.out.println("原本数量1："+Double.valueOf(originstore.getSnum())+"--"+"增加数量："+Double.valueOf(productionStore.getSnum()) / 1000+"--"+"现在数量："+newsnum);
            }else {
                //  获取增加后的数量
                newsnum = String.valueOf(Double.valueOf(originstore.getSnum()) + (Double.valueOf(productionStore.getSnum()) / 1000));
                System.out.println("原本数量2："+Double.valueOf(originstore.getSnum())+"--"+"增加数量："+Double.valueOf(productionStore.getSnum()) / 1000+"--"+"现在数量："+newsnum);
            }
        }
        productionStore.setSnum(newsnum);
        productionStore.setSunit("吨");
        productionStore.setSyield(newsnum+"吨");
        producedMapper.modifyProducedStore(productionStore);
    }
    //  物品入库
    @Override
    public void addStore(ProductionStore productionStore) {
        //  入库商品的gid
        int gid = unloadGoodsMapper.findGidByName(productionStore.getSname());
        //  入库商品的库存
        int num = unloadGoodsMapper.findStockByGid(productionStore.getSname());
        //  入库量
        int cnum = (int) (Double.valueOf(productionStore.getSnum())*1000);

        GoodsEntity goodsEntity = new GoodsEntity();
        goodsEntity.setGname(productionStore.getSname());
        UnloadGoods unloadGoods = new UnloadGoods(null,productionStore.getSname(),goodsEntityMapper.selectAll(goodsEntity).get(0).getGoodsUniqueNo(),gid,num,cnum, productionStore.getEname(),null,productionStore.getTime().replace("-","/"),10,"未入库","生产部入库",null,"生产入库","李四",null,null,null,null,null);
        unloadGoodsService.addUnloadGoodsIsProduct(unloadGoods);
        //  入库成功后，生产仓储清空
        productionStore.setSnum("0");
        productionStore.setPressure("库存正常");
        productionStore.setSyield("0吨");
        producedMapper.modifyProducedStore(productionStore);
    }


}
